import triton
import triton.language as tl
import torch
import torch_npu

from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math

from .util import triton_helper_compile, compiled_kernel_list

# triton_per_fused_add_mean_mul_pow_rsqrt_14
@triton.jit
def fused_kernel7(in_out_ptr0, in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, out_ptr1, xnumel, rnumel):
    xnumel = 9
    XBLOCK: tl.constexpr = 1
    rnumel = 2048
    RBLOCK: tl.constexpr = 2048
    xoffset = tl.program_id(0) * XBLOCK
    xindex = tl.full([1], xoffset, tl.int32)
    xmask = tl.full([RBLOCK], True, tl.int1)
    rindex = tl.arange(0, RBLOCK)[:]
    roffset = 0
    rmask = tl.full([RBLOCK], True, tl.int1)
    r1 = rindex
    x0 = xindex
    tmp0 = tl.load(in_out_ptr0 + (r1 + (2048*x0)), None)
    tmp1 = tl.load(in_ptr0 + (r1 + (2048*x0)), None)
    tmp3 = tl.load(in_ptr1 + (r1 + (2048*x0)), None)
    tmp5 = tl.load(in_ptr2 + (r1 + (2048*x0)), None)
    tmp7 = tl.load(in_ptr3 + (r1 + (2048*x0)), None)
    tmp13 = tl.load(in_ptr4 + (r1), None, eviction_policy='evict_last')
    tmp2 = tmp0 + tmp1
    tmp4 = tmp2 + tmp3
    tmp6 = tmp4 + tmp5
    tmp8 = tmp6 + tmp7
    tmp9 = tmp8 * tmp8
    tmp10 = tl.broadcast_to(tmp9, [RBLOCK])
    tmp12 = triton_helpers.promote_to_tensor(tl.sum(tmp10, 0))
    tmp14 = 2048.0
    tmp15 = tmp12 / tmp14
    tmp16 = 1e-05
    tmp17 = tmp15 + tmp16
    tmp18 = libdevice.rsqrt(tmp17)
    tmp19 = tmp8 * tmp18
    tmp20 = tmp13 * tmp19
    tl.store(in_out_ptr0 + (r1 + (2048*x0)), tmp8, None)
    tl.store(out_ptr1 + (r1 + (2048*x0)), tmp20, None)

def test_compile_for_fused_kernel7():
    signature = {0: '*fp32', 1: '*fp32', 2: '*fp32', 3: '*fp32', 4: '*fp32', 5: '*fp32', 6: '*fp32', 7: 'i32', 8: 'i32'}
    triton_helper_compile(func=fused_kernel7, signature=signature)

compiled_kernel_list["fused_kernel7"] = test_compile_for_fused_kernel7